package com.example.demo.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.demo.common.tools.DateTool;
import com.example.demo.common.tools.JwtUtil;
import com.example.demo.sys.entity.Homewrok;
import com.example.demo.sys.entity.Student;
import com.example.demo.sys.entity.Teacher;
import com.example.demo.sys.mapper.StudentMapper;
import com.example.demo.sys.mapper.TeacherMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.demo.controller.Result;
import com.example.demo.sys.mapper.UserMapper;
import com.example.demo.sys.entity.User;

import com.example.demo.common.tools.BaseController;


import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器 chrimer
 * </p>
 *
 */
@RestController
@RequestMapping("/sys/user")
@CrossOrigin
public class UserController extends BaseController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    HttpServletRequest request;

    Logger logger = LoggerFactory.getLogger(getClass());


    @RequestMapping(method = RequestMethod.GET, value = "/test")
    public Result Test() {
        Result result = new Result();
        return result;

    }

    @RequestMapping(method = RequestMethod.POST, value = "/postTest")
    public Result postTest(String username,String password) {
        Result result = new Result();
        if("root".equals(username)&&"root".equals(password)){
            return result;
        }else{
            result.fail("用户名或密码错误");
        }
        return result;

    }


    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public Result login(String username, String password,String role) {

        Result result = new Result();

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        User userExit = userMapper.selectOne(new QueryWrapper<User>(user));
        if (userExit == null) {
            result.fail("用户名或密码错误");

        }
        else if(!role.equals(userExit.getRole())){
            result.unauthorized("权限不足");
        }
        else {
            Map<String, Object> map = new HashMap<>();
            map.put("user", userExit);
            map.put("token", JwtUtil.generateToken(userExit.getId()));
            result.setData(map);
        }
        return result;

    }

    @RequestMapping(method= RequestMethod.POST,value="/page")
    public Result page(
            Integer pageNum,
            Integer pageSize,
            String nickname) {

        Result result = new Result();
        Page<User> page = new Page<User>(pageNum, pageSize);
        User parms = new User();
        QueryWrapper<User> warpper = new QueryWrapper<User>(parms);
        if(nickname!=null&&!"".equals(nickname)){//普通管理员搜索
            warpper.eq("nickname",nickname);
        }
        else if (nickname!=null&&!"".equals(nickname)) {
            warpper.eq("nickname",nickname);
        }
        result.setData(userMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method= RequestMethod.POST,value="/save")
    public Result save(@RequestBody User entity) {
        Result result = new Result();
        if (entity.getId() == null) {
            userMapper.insert(entity);
        } else {//updateById
            userMapper.updateById(entity);
        }
        return result;
    }

    @RequestMapping(method= RequestMethod.POST,value="/alterpassword")
    public Result alterpassword(
            String id,
            String password,
            String email,
            String role) {
        Result result = new Result();
        Student student = new Student();
        Teacher teacher = new Teacher();
        if(role.equals("学生")){ student.setUserid(id);
            student.setEmail(email);
            Student studentExit = studentMapper.selectOne(new QueryWrapper<Student>(student));
            if(studentExit!= null) userMapper.UpdatePassword(id,password);
            else result.fail("信息不对，修改失败");
        }
        else if(role.equals("老师")){
            teacher.setUserid(id);
            teacher.setEmail(email);
            Teacher teacherExit = teacherMapper.selectOne(new QueryWrapper<Teacher>(teacher));
            if(teacherExit!= null) userMapper.UpdatePassword(id,password);
            else result.fail("信息不对，修改失败");
        }
        return result;
    }

    @RequestMapping(method= RequestMethod.DELETE,value="/delete")
    public Result delete( String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
        userMapper.deleteBatchIds(deleteIds);
        return result;
    }

    @RequestMapping(method= RequestMethod.POST,value="/register")
    public Result register(@RequestBody User entity) {
        Result result = new Result();
        User user = new User();
        user.setUsername(entity.getUsername());
        user.setRole(entity.getRole());
        User userExit = userMapper.selectOne(new QueryWrapper<User>(user));
        if (userExit == null) {
            entity.setCreatTime(DateTool.getCurrTime());
            entity.setStatus(1);
            userMapper.insert(entity);
            if(entity.getRole().equals("学生")){
                Student student = new Student();
                student.setUserid(entity.getId());
                student.setEmail("0");
                student.setTel("0");
                student.setInterest("0");
                student.setStudentname(entity.getNickname());
                student.setSex("男");
                student.setCreatTime(DateTool.getCurrTime());
                studentMapper.insert(student);
            }
            else{
                Teacher teacher = new Teacher();
                teacher.setUserid(entity.getId());
                teacher.setEmail("0");
                teacher.setTel("0");
                teacher.setExperience("0");
                teacher.setTeachername(entity.getNickname());
                teacher.setSex("男");
                teacher.setField("0");
                teacher.setCreatTime(DateTool.getCurrTime());
                teacherMapper.insert(teacher);
            }

            result.success("操作成功");
        }
        else  result.fail("账号已存在");

        return result;
    }
    //启用禁用
    @RequestMapping(method= RequestMethod.POST,value="/updateUseful")
    public Result updateUseful(String ids, Integer status){
        Result result = new Result();
        String[] aryIds = ids.split(",");
        for(String id : aryIds){
            userMapper.updateUseful(id,status);
        }

        result.success("更新成功");
        return result;
    }

    @RequestMapping(method= RequestMethod.POST,value="/alter")//修改密码
    public Result alter(
            String username,
            String role,
            String tel,
            String newpassword) {

        Result result = new Result();
        User user = new User();
        Student student = new Student();
        Teacher teacher = new Teacher();
        user.setRole(role);
        user.setUsername(username);
        User userExit = userMapper.selectOne(new QueryWrapper<User>(user));
        if(userExit!=null)
        {
            String userid = userMapper.SelectId(username,role);
            if(role.equals("学生")){
                student.setUserid(userid);
                student.setTel(tel);
                Student studentExit = studentMapper.selectOne(new QueryWrapper<Student>(student));
                if (studentExit!=null) {
                    userMapper.UpdatePassword(userid, newpassword);
                    result.success("操作成功");
                }
                else result.fail("信息不对，修改失败");
            }
            else if(role.equals("老师")){
                teacher.setUserid(userid);
                teacher.setTel(tel);
                Teacher teacherExit = teacherMapper.selectOne(new QueryWrapper<Teacher>(teacher));
                if (teacherExit!=null) {
                    userMapper.UpdatePassword(userid, newpassword);
                    result.success("操作成功");
                }
                else result.fail("信息不对，修改失败");
            }

            else result.fail("信息不对，修改失败");

        }
        else result.fail("信息不对，修改失败");
        return result;
    }
}
